// pages/product/buy.js
import api from '../../api/index'
import { CHINA_NORTH_REGION, CHINA_NORTH_REGION_1 } from '../../store/region'
import { userInfoStore } from '../../store/userInfo'
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasRelationShop:false,
    pshow: false,
    cshow: false,
    dshow: false,
    plist: [],
    clist: [],
    dlist: [],
    privince: {},
    city: {},
    district: {},
    product: null,
    shoplist: [],
    selectshop: 0,
    buyNumber:1,
    proAmount: 0,
    cpnAmount: 0,
    contact:'',
    telphone:'',
    address:'',
    remarks: '',
    objectArray: CHINA_NORTH_REGION,

    adrPShow:false,
    adrCShow: false,
    adrPlist:[],
    adrClist: [],
    adrPrivince: {},
    adrCity: {},
    adrArray:CHINA_NORTH_REGION_1,


    sku:null,
    canUseCoupons:null,
    notUseCoupons:null,
    mayBuyCoupons:null,
    showNotUse:false,
    
    saleRegion:null,
    maskHidden:false,
    selectCoupons:[],
    buyCoupons:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    if (options.sku){
      let skuStr = decodeURIComponent(options.sku)
      console.log(skuStr)
      this.setData({
        sku: JSON.parse(skuStr),
        buyNumber: options.num,
      },()=>{
        self.getProductDetail(options.id);
      })
    }else{
      this.getProductDetail(options.id);
    }
  },

  onShow: function () {
  },

  showNotUse:function(){
    this.setData({
      showNotUse: !this.data.showNotUse
    });
  },

  buyCoupon:function(e){
    let item = e.currentTarget.dataset.item;
    let rds;
    let ca = 0;
    this.data.buyCoupons=[];
    for (let i = 0; i < this.data.mayBuyCoupons.length; i++) {
      rds = this.data.mayBuyCoupons[i];
      if (rds.id == item.id) {
        rds.select = !rds.select;
      }
      if (rds.select){
        ca = ca + rds.buyPrice;
        this.data.buyCoupons.push(rds.id);
      }
    }
    this.setData({
      mayBuyCoupons: this.data.mayBuyCoupons,
      buyCoupons: this.data.buyCoupons,
      cpnAmount: ca
    })
  },

  useCoupon:function(e){
    // console.log(e.currentTarget.dataset.item)
    let item = e.currentTarget.dataset.item; 
    let rds;
    this.data.selectCoupons=[];
    for (let i = 0; i < this.data.canUseCoupons.length; i++){
      rds = this.data.canUseCoupons[i];
      if (rds.id == item.id){
        rds.select = !rds.select;
      }
      if (rds.select) {
        this.data.selectCoupons.push(rds.id)
      }
    }
    this.setData({
      canUseCoupons: this.data.canUseCoupons,
      selectCoupons: this.data.selectCoupons
    })  
    
  },

  showPayDetail:function(){
    this.setData({ maskHidden: true });
  },

  hideDetail:function(){
    this.setData({ maskHidden:false});
  },

  getMayBuyCoupons: function () {
    let self = this
    let param = {
      openId: userInfoStore.userInfo.openId,
      productId: this.data.product.id,
      payShopId: this.data.selectshop
    }
    
    
  },

  getCanUseCoupons: function () {
    let self = this
    let param = {
      openId: userInfoStore.userInfo.openId,
      productId: this.data.product.id,
      payShopId: this.data.selectshop
    }
    
  },

  getNotUseCoupons:function () {
    let self = this
    let param = {
      openId: userInfoStore.userInfo.openId,
      productId: this.data.product.id,
      payShopId: this.data.selectshop
    }
    

  },

  getProductDetail: function (id) {
    let self = this
    api.getproductdetail({ productId: id }).then(res => {
      let { result } = res;
      for (let i = 0; i < result.images.length; i++) {
        if (result.images[i].imageType == 1) {
          result.thumImage = result.images[i].imagePath;
          break;
        }
      }
      //**指定了该销售服务商就不考虑销售区域 */
      if (result.saleDistributors.length>0) {
        self.setData({
          product: result,
          proAmount: parseFloat(result.preMoney) * self.data.buyNumber,
          shoplist: result.saleDistributors, 
          hasRelationShop: true
        });
      } else {
        api.getScope({ productId: id }).then(res => {
          let { result } = res;
          
            self.setData({
              saleRegion: result
            }, () => {
              api.getuserrelationshop({ openId: userInfoStore.userInfo.openId }).then(res => {
                let { result } = res;
                if (result.length > 0) {
                  if(self.data.saleRegion.length>0){
                    let s = self.searchShopList(self.data.saleRegion, result);
                    self.setData({ shoplist: s, hasRelationShop: true });
                  }else{
                    self.setData({ shoplist: result, hasRelationShop: true });
                  }
                }
              })
            })
           
        });
        self.setData({
          product: result,
          proAmount: parseFloat(result.preMoney) * self.data.buyNumber
        });
      }

    })
  },

  searchShopList:function(saleRegion, shopList){
    let shop,region;
    let sl = [];
    for (let i = 0; i < shopList.length; i++) {
      shop = shopList[i]
      for (let j = 0; j < saleRegion.length; j++){
        region = saleRegion[j];
        if (region.province == shop.province){
          if (region.city==shop.city){
            if (region.district == shop.district){
              sl.push(shop)
            } else if (!region.district){
              sl.push(shop)
            }
          } else if (!region.city) {
            sl.push(shop)
          }
        } 
      }
    }
    return sl;
  },

  getShopList:function(){
    let param = {
      province: (this.data.privince.regname ? this.data.privince.regname : ''),
      city: (this.data.city.regname ? this.data.city.regname : ''),
      district: (this.data.district.regname ? this.data.district.regname : '')
    }
    let self = this;
    api.getshoplist(param).then(res => {
      if (self.data.saleRegion.length > 0) {
        let s = self.searchShopList(self.data.saleRegion, res.result);
        self.setData({ shoplist: s, selectshop: 0 });
      } else {
        self.setData({ shoplist: res.result, selectshop: 0 });
      }

    });
  },

  selectByParid:function(pid){
    let list = [];
    for (var i = 0; i < this.data.objectArray.length; i++) {
      if (this.data.objectArray[i].parid == pid) {
        list.push(this.data.objectArray[i])
      }
    }
    return list;
  },

  selectByParid1: function (pid) {
    let list = [];
    for (var i = 0; i < this.data.adrArray.length; i++) {
      if (this.data.adrArray[i].parid == pid) {
        list.push(this.data.adrArray[i])
      }
    }
    return list;
  },

  selectTap:function(e){
    let idx = e.currentTarget.dataset.idx;
    if (idx == 1) {
      if (!this.data.pshow){
        let list = this.selectByParid("1");
        this.setData({
          pshow: !this.data.pshow,
          plist: list,
          clist:[],
          dlist:[],
          privince: {},
          city: {},
          district: {}
        })
      } else {
        this.setData({
          pshow: !this.data.pshow
        })
      }
    }
    if (idx == 2 && this.data.privince.regid) {
      if (!this.data.cshow) {
        let list = this.selectByParid(this.data.privince.regid);
        this.setData({
          cshow: !this.data.cshow,
          clist: list,
          dlist: [],
          city: {},
          district: {}
        })
      } else {
        this.setData({
          cshow: !this.data.cshow
        })
      }
    }
    if (idx == 3 && this.data.city.regid) {
      if (!this.data.dshow) {
        let list = this.selectByParid(this.data.city.regid);
        this.setData({
          dshow: !this.data.dshow,
          dlist: list,
          district: {}
        })        
      } else {
        this.setData({
          dshow: !this.data.dshow
        })
      }
    }
  },

  optionTap: function(e) {
    
    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let self = this;
    if (idx == 1) {
      this.setData({
        privince: this.data.plist[index],
        pshow: !this.data.pshow,
        selectshop:0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 2) {
      this.setData({
        city: this.data.clist[index],
        cshow: !this.data.cshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 3) {
      this.setData({
        district: this.data.dlist[index],
        dshow: !this.data.dshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
  },

  selectAddressTap:function(e){
    let idx = e.currentTarget.dataset.idx;
    if (idx == 1) {
      if (!this.data.adrPShow) {
        let list = this.selectByParid1("1");
        this.setData({
          adrPShow: !this.data.adrPShow,
          adrPlist: list,
          adrClist: [],
          adrPrivince: {},
          adrCity: {}
        })
      } else {
        this.setData({
          adrPShow: !this.data.adrPShow
        })
      }
    }
    if (idx == 2 && this.data.adrPrivince.regid) {
      if (!this.data.adrCShow) {
        let list = this.selectByParid1(this.data.adrPrivince.regid);
        this.setData({
          adrCShow: !this.data.adrCShow,
          adrClist: list,
          adrCity: {}
        })
      } else {
        this.setData({
          adrCShow: !this.data.adrCShow
        })
      }
    }
  },

  optionAddressTap:function(e){
    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let self = this;
    if (idx == 1) {
      this.setData({
        adrPrivince: this.data.adrPlist[index],
        adrPShow: !this.data.adrPShow
      });
    }
    if (idx == 2) {
      this.setData({
        adrCity: this.data.adrClist[index],
        adrCShow: !this.data.adrCShow
      });
    }    
  },

  buy: function () {
    if (this.data.product) {
      if (this.data.product.status != 1) {
        wx.showToast({
          icon: "none",
          title: "敬请期待!"
        })
        return;
      }
    }
    let limit = 5;
    if (this.data.sku && this.data.sku.stock) limit = this.data.sku.stock;
    if (this.data.buyNumber <= 0 || this.data.buyNumber > limit) {
      wx.showToast({
        icon: "none",
        title: "请重新选定数量!"
      })
      return;
    }
    if (this.data.selectshop==0){
      wx.showToast({
        icon: "none",
        title: "请选择服务的商家!"
      })
      return;
    }
    if (this.data.contact.length == 0){
      wx.showToast({
        icon: "none",
        title: "请填写联系人!"
      })
      return;
    }
    if (this.data.telphone.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请填写电话!"
      })
      return;
    }
    if (this.data.address.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请填写详细安装地址!"
      })
      return;
    }
    let adr = '';
    if (this.data.adrPrivince.regname) adr += this.data.adrPrivince.regname;
    if (this.data.adrCity.regname) adr += this.data.adrCity.regname;
    adr += this.data.address;
    // console.log(adr)
    // return;
    if (this.data.product) {

      let odrStr = {
        shopId: this.data.selectshop,
        payable: (this.data.proAmount + this.data.cpnAmount),
        payment: (this.data.proAmount + this.data.cpnAmount),
        payType: 1,
        contact: this.data.contact,
        telphone: this.data.telphone,
        address: adr,
        remarks: this.data.remarks
      };
      let goods = {
        productId: this.data.product.id,
        number: this.data.buyNumber,
        payable: this.data.proAmount,
        payment: this.data.proAmount
      };
      if (this.data.sku) {
        goods = Object.assign(goods, { skuId: this.data.sku.skuId })
        goods = Object.assign(goods, { skuName: this.data.sku.skuName })
      }
      let goodss = [goods];

      let param = {
        openId: userInfoStore.userInfo.openId,
        order: odrStr,
        goodsList: goodss
      }
      // if (this.data.selectCoupons.length>0) {
      //   param = Object.assign(param, { useCoupons: this.data.selectCoupons})
      // }
      param = Object.assign(param, { useCoupons: this.data.selectCoupons })
      
      // if (this.data.buyCoupons.length>0) {
      //   param = Object.assign(param, { buyCoupons: this.data.buyCoupons })
      // }
      param = Object.assign(param, { buyCoupons: this.data.buyCoupons })
      // console.log(JSON.stringify(param))

      api.getProductOrder20200907(param).then(res=>{
        let { result } = res;
        wx.requestPayment({
          'timeStamp': result.timeStamp,
          'nonceStr': result.nonceStr,
          'package': result.package,
          'signType': result.signType,
          'paySign': result.paySign,
          'success': function (res) {
            wx.showModal({
              title: '提示',
              content: '支付成功',
              showCancel:false,
              success: (res) => {
                wx.switchTab({
                  url: '/pages/clickMe/index',
                })
              }
            });
          },
          'fail': function (res) {
            let orderid = result.orderId.substring(4);
            api.orderCancel({ orderId: orderid})
            wx.showModal({
              title: '提示',
              content: '支付失败',
              showCancel: false,
              success: (res) => {
                wx.switchTab({
                  url: '/pages/clickMe/index',
                })
              }
            });
            return;
          },
          'complete': function (res) {
            console.log('complete===',res);
          }
        });
      },err=>{
        wx.showToast({
          icon: "none",
          title: err
        })
      });
    }
  },

  radioChange: function(e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value);
    this.setData({ selectshop: e.detail.value, showNotUse:false});
    // this.getCanUseCoupons();
    // this.getNotUseCoupons();
    // this.getMayBuyCoupons();

  },

  raiseNumber: function(e) {
    let num = parseInt(this.data.buyNumber);
    num++;
    let proa = parseFloat(this.data.product.preMoney) * num;
    this.setData({ 
      buyNumber: num,
      proAmount: proa
    })
  },

  reduceNumber: function(e) {
    let num = parseInt(this.data.buyNumber);
    num--;
    let proa = parseFloat(this.data.product.preMoney) * num;
    this.setData({ 
      buyNumber: num,
      proAmount: proa
    })
  },

  bindKeyContactInput: function (e) {
    this.setData({
      contact: e.detail.value.replace(/\s+/g, '')
    });
  },

  bindKeyTelInput: function (e) {
    this.setData({
      telphone: e.detail.value.replace(/\s+/g, '')
    });
  },

  bindKeyAdrInput: function (e) {
    this.setData({
      address: e.detail.value.replace(/\s+/g, '')
    });
  },

  bindTextAreaBlur: function(e) {
    this.setData({ remarks: e.detail.value});
  }
  
})